import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
  subCount: 0,
  carGoods: {},
  street: '',
  address: {}
}

// 获取本地存储值
function getLocalState(state) {
  if (localStorage.state) {
    state.subCount = JSON.parse(localStorage.state).subCount
    state.carGoods = JSON.parse(localStorage.state).carGoods
  } else {
    state.subCount = 0
    state.carGoods = {}
  }
}

getLocalState(state)

function setLocalState(state) {
  localStorage.state = JSON.stringify(state)
}

const mutations = {
  addGoods(state, good) {
    let id = good.id
    state.carGoods[id] = good.quantity
    state.subCount = 0
    for (let key in state.carGoods) {
      state.subCount += state.carGoods[key]
    }
    setLocalState(state)
  },
  delGoods(state, good) {
    let id = good.id
    // console.log(good.quantity)
    if (good.quantity <= 0) {
      delete state.carGoods[id]
      state.subCount = 0
      for (let key in state.carGoods) {
        state.subCount += state.carGoods[key]
      }
      setLocalState(state)
    } else {
      state.carGoods[id] = good.quantity
      state.subCount = 0
      for (let key in state.carGoods) {
        state.subCount += state.carGoods[key]
      }
      // console.log(state.subCount)
      setLocalState(state)
    }
  },
  setGoods(state, good) {
    if (Object.keys(good).length !== 0) {
      let id = good.id

      state.carGoods[id] = good.quantity
      let sum = 0
      for (let key in state.carGoods) {
        sum += state.carGoods[key]
      }

      state.subCount = sum

      console.log(state.subCount)
      setLocalState(state)
    } else {
      state.subCount = 0
      state.carGoods = {}
      setLocalState(state)
    }
  },
  setStreet(state, street) {
    state.street = street
    setLocalState(state)
  },
  setAddress(state, addressInfo) {
    state.address = addressInfo
    setLocalState(state)
  }
}

// 异步修改状态
const actions = {
  addsubCount(context) {
    context.commit('add')
    setLocalState(state)
  },
  setsubCount(context, num) {
    state.subCount = num
    setLocalState(state)
  },
  reducesubCount(context) {
    context.commit('reduce')
    setLocalState(state)
    if (state.subCount <= 0) {
      state.subCount = ''
    }
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions
})
